package com.gxa.service.user.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.common.constant.ScommunityConstant;
import com.gxa.common.exception.RRException;
import com.gxa.common.utils.CommonUtils;
import com.gxa.dto.userdto.MenuDto;
import com.gxa.entity.user.SysMenu;
import com.gxa.entity.user.SysRole;
import com.gxa.entity.user.SysUser;
import com.gxa.service.user.SysMenuService;
import com.gxa.mapper.user.SysMenuMapper;
import com.gxa.service.user.SysRoleService;
import com.gxa.service.user.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author Administrator
* @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
* @createDate 2022-10-19 17:50:23
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;


    @Override
    public List<SysMenu> selectMenuListByUsername(String username) {
        List<SysMenu> menuList = null;
        try {
            menuList = this.menuMapper.selectMenuListByUsername(username);
        }catch (Exception e){
            e.printStackTrace();
        }
        return menuList;
    }

    @Override
    public List<SysMenu> getUserMenu(String username) {
        // 得到用户所有菜单
        List<SysMenu> menus = this.menuMapper.selectMenuListByUsername(username);
        // 最终的菜单数据
        List<SysMenu> rootMuns = new ArrayList<>();
        //格式化 得到树形菜单
        return getTreeMenus(menus, rootMuns);
    }

    public List<MenuDto> mygetUserMenu(String username) {
        // 得到用户所有菜单
        List<MenuDto> menus = this.menuMapper.myselectMenuListByUsername(username);
        // 最终的菜单数据
        List<MenuDto> rootMuns = new ArrayList<>();
        //格式化 得到树形菜单
        return mygetTreeMenus(menus, rootMuns);
    }

    @Override
    public List<SysMenu> getAllMenusWithTree() {
        // 得到所有菜单
        List<SysMenu> allMenusWithTree = this.menuMapper.getAllMenusWithTree();
        // 最终的菜单数据
        List<SysMenu> rootMenus = new ArrayList<>();
        return getTreeMenus(allMenusWithTree, rootMenus);
    }

    @Override
    public List<String> getRoleMenus(String roleId) {
        List<String> roleMenuIds = null;
        try {
            roleMenuIds = this.menuMapper.getRoleMenus(roleId);
        }catch (Exception e){
            throw new RRException("获得角色菜单资源失败!");
        }
        return roleMenuIds;
    }

    @Override
    public IPage<SysMenu> getAllMenusTable(Integer currentPage, Integer pageSize, String name, String parentId) {
        IPage<SysMenu> menuPage = null;
        try {
            Page<SysMenu> page = new Page<>(currentPage,pageSize);
            menuPage = this.menuMapper.selectMenuListByParam(page,name, parentId);
        }catch (Exception e){
            e.printStackTrace();
            throw  new RRException("菜单分页查询失败");
        }

        return menuPage;
    }

    @Override
    public boolean saveOrUpdateMenu(SysMenu menu) {
        boolean isAdd = false;
        SysUser currentUser = this.userService.getCurrentUser();
        if(StringUtils.isBlank(menu.getId())){
            menu.setId(CommonUtils.getUUID());
            this.createEntity(menu,currentUser);
            this.updateEntity(menu,currentUser);
            this.save(menu);
            isAdd = true;
        }else{
            this.updateEntity(menu,currentUser);
            this.updateById(menu);
        }
        return isAdd;
    }

    @Override
    public void deleteMenus(String id) {
        // 查询该菜单是否已经绑定角色
        List<SysRole> roles = this.roleService.selectRoleByMenuId(id);
        if(null != roles && roles.size()>0){
            throw new RRException("该菜单已被角色绑定，无法删除");
        }
        //  删除菜单信息
        this.baseMapper.deleteById(id);
    }

    public void updateEntity(SysMenu menu, SysUser currentUser) {
        if (null != menu) {
            menu.setUpdator(currentUser.getId());
            menu.setUpdatorName(currentUser.getUsername());
        }
        menu.setUpdateTime(new Date());
    }

    public void createEntity(SysMenu menu,SysUser currentUser) {
        if (null != menu) {
            menu.setCreator(currentUser.getId());
            menu.setCreatorName(currentUser.getUsername());
        }
        menu.setCreateTime(new Date());
    }

    /**
     * 得到树形菜单数据集合
     * @param menus 查询出的所有菜单集合
     * @param rootMenus 最终返回的菜单集合
     */
    public List<SysMenu> getTreeMenus(List<SysMenu> menus, List<SysMenu> rootMenus){
        // 得到根菜单（一级菜单）
        for (SysMenu menu: menus) {
            if(StringUtils.isBlank(menu.getParentId()) || ScommunityConstant.ROOT_MENU.equals(menu.getParentId())){
                rootMenus.add(menu);
            }
        }
        //排序  Collections.sort(rootMenu, order());
        // 遍历根菜单
        for (SysMenu menu: rootMenus) {
            //得到该根菜单所属的子菜单
            List<SysMenu> childMenus = this.getChildMenu(menu.getId(), menus);
            menu.setChildren(childMenus);
        }
        return rootMenus;
    }


    /**
     * 得到子菜单数据
     * @param parentsId 父菜单ID
     * @param menus 所有菜单集合
     */
    public List<SysMenu> getChildMenu(String parentsId,List<SysMenu> menus) {
        //子菜单
        List<SysMenu> childMenus =  new ArrayList<>();
        for (SysMenu menu:menus) {
            // 如果该菜单的父Id是传入ID 则为转入菜单的子菜单
            if(parentsId.equals(menu.getParentId())){
                childMenus.add(menu);
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (SysMenu menu : childMenus) {
            // 递归查询
            menu.setChildren(getChildMenu(menu.getId(), menus));
        }
        //排序
        // 递归退出条件
        if (childMenus.size() == 0) {
            return null;
        }
        return childMenus;
    }

    /**
     * 得到树形菜单数据集合
     * @param menus 查询出的所有菜单集合
     * @param rootMenus 最终返回的菜单集合
     */
    public List<MenuDto> mygetTreeMenus(List<MenuDto> menus, List<MenuDto> rootMenus){
        // 得到根菜单（一级菜单）
        for (MenuDto menu: menus) {
            if(StringUtils.isBlank(menu.getParentId()) || ScommunityConstant.ROOT_MENU.equals(menu.getParentId())){
                rootMenus.add(menu);
            }
        }
        //排序  Collections.sort(rootMenu, order());
        // 遍历根菜单
        for (MenuDto menu: rootMenus) {
            //得到该根菜单所属的子菜单
            List<MenuDto> childMenus = this.mygetChildMenu(menu.getId(), menus);
            menu.setChildren(childMenus);
        }
        return rootMenus;
    }


    /**
     * 得到子菜单数据
     * @param parentsId 父菜单ID
     * @param menus 所有菜单集合
     */
    public List<MenuDto> mygetChildMenu(String parentsId,List<MenuDto> menus) {
        //子菜单
        List<MenuDto> childMenus =  new ArrayList<>();
        for (MenuDto menu:menus) {
            // 如果该菜单的父Id是传入ID 则为转入菜单的子菜单
            if(parentsId.equals(menu.getParentId())){
                childMenus.add(menu);
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (MenuDto menu : childMenus) {
            // 递归查询
            menu.setChildren(mygetChildMenu(menu.getId(), menus));
        }
        //排序  Collections.sort(rootMenu, order());
        // 递归退出条件
        if (childMenus.size() == 0) {
            return null;
        }
        return childMenus;
    }

}




